#!/usr/bin/env python3


#  Uruk Video Downloader (UVD)
#  
#  Copyright 2020 hayder majid <hayder@riseup.net>
#  
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#  
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#  
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#  MA 02110-1301, USA.
#  
# 

from tkinter import *
from tkinter import filedialog
from tkinter import messagebox
import os

gui=Tk()
gui.resizable(False, False)
gui.configure(background='#f5f6fa')
gui.title("Uruk Video Downloader")
gui.iconphoto(True, PhotoImage(file='/usr/share/pixmaps/uvd.png'))
audioVal = IntVar(value=0)
qualityVal = IntVar(value=0)

def pList_input():
    inputValue=textBox.get("1.0","end-1c")
    fileRead()
    aVal = audioVal.get()
    qVal = qualityVal.get()
    if aVal == 1 :
        os.system("xterm -e youtube-dl -c -x --audio-format mp3 -o "+(outPath)+"/'%(title)s.%(ext)s' "+(inputValue))#+' | zenity  --progress --title="Downloading Progress" --text="Please Wait While your Download finished..." --pulsate --auto-close')
    else :
        if qVal == 1 :
            os.system("xterm -e youtube-dl -c -f mp4 -o "+(outPath)+"/'%(title)s.%(ext)s' "+(inputValue))#+' | zenity  --progress --title="Downloading Progress" --text="Please Wait While your Download finished..." --pulsate --auto-close')
        else :
            os.system("xterm -e youtube-dl -c -o "+(outPath)+"/'%(title)s.%(ext)s' "+(inputValue))#+' | zenity  --progress --title="Downloading Progress" --text="Please Wait While your Download finished..." --pulsate --auto-close'

def sList_input():
    inputValue=textBox.get("1.0","end-1c")
    fileRead()
    aVal = audioVal.get()
    qVal = qualityVal.get()
    if aVal == 1 :
        try:
            os.system("xterm -e youtube-dl -c -x --audio-format mp3 --no-playlist -o "+(outPath)+"/'%(title)s.%(ext)s' "+(inputValue))#+' | zenity  --progress --title="Downloading Progress" --text="Please Wait While your Download finished..." --pulsate --auto-close')
            messageEnd
        except KeyboardInterrupt:
            messagebox.showinfo(title="Download Interrupted", message="Your download is not complete! \n You just interrputed your process")
    else :
        if qVal == 1 :
            os.system("xterm -e youtube-dl -c -f mp4 --no-playlist -o "+(outPath)+"/'%(title)s.%(ext)s' "+(inputValue))#+' | zenity  --progress --title="Downloading Progress" --text="Please Wait While your Download finished..." --pulsate --auto-close')
        else :
            try:
                os.system("xterm -e youtube-dl -c --no-playlist -o "+(outPath)+"/'%(title)s.%(ext)s' "+(inputValue))#+' | zenity  --progress --title="Downloading Progress" --text="Please Wait While your Download finished..." --pulsate --auto-close')
                messageEnd
            except KeyboardInterrupt:
                messagebox.showinfo(title="Download Interrupted", message="Your download is not complete! \n You just interrputed your process")
        
    

def messageEnd():
    messagebox.showinfo(title="Download Complete", message="Your download is complete!")

def eClear():
    textBox.delete('1.0', END)
    textBox.update()

def messageBox():
    messagebox.showinfo(title="About Uruk Video Downloader", message="Uruk Video Downloader \n Simple Free and Open Source Youtube Video Downloader \n by hayder majid \n <hayder@riseup.net> \n version 1.0 \n under (GPLv3) 2020 ")

def cMenu(w):
    global menu
    menu = Menu(w, tearoff=0)
    menu.add_command(label="Cut")
    menu.add_command(label="Copy")
    menu.add_command(label="Paste")

def sMenu(e):
    w = e.widget
    menu.entryconfigure("Cut", command=lambda: w.event_generate("<<Cut>>"))
    menu.entryconfigure("Copy", command=lambda: w.event_generate("<<Copy>>"))
    menu.entryconfigure("Paste", command=lambda: w.event_generate("<<Paste>>"))
    menu.tk.call("tk_popup", menu, e.x_root, e.y_root)
    
def fileRead():
    global outPath
    folderPath = os.environ['HOME']+'/.uvd'
    outDir = open(folderPath+'/outPath.txt', "r")
    outPath = str(outDir.readline())
    outDir.close()

def fileCh():
    fileRead()
    if outPath == "":
        messagebox.showinfo(title="Change Download Path", message="UVD is using now the Default Download path \n in 'Videos' Folder!")
        folderPath = os.environ['HOME']+'/.uvd'
        oldPath = open(folderPath+'/outPath.txt', "w")
        oldPath.write('/$HOME/Videos')
        oldPath.close()
        fileRead()
    os.system('xdg-open '+outPath)

def cUpdate():
    os.system("pkexec pip3 install --upgrade youtube-dl")
    messagebox.showinfo(title="Checking For Update", message="Checking For Update is Completed!")

def browsePath():
    fileName = str(filedialog.askdirectory())
    folderPath = os.environ['HOME']+'/.uvd'
    oldPath = open(folderPath+'/outPath.txt', "w")
    oldPath.write(fileName)
    oldPath.close()
    if fileName == '()':
        messagebox.showwarning(title="Change Download Path", message="You did not Select any Path, UVD is using now the Default \n Download path in 'Videos' Folder!")
        folderPath = os.environ['HOME']+'/.uvd'
        oldPath = open(folderPath+'/outPath.txt', "w")
        oldPath.write('/$HOME/Videos')
        oldPath.close()

labelWindow = Label(gui,text = "Uruk Video Downloader \n -------------------------------------------", fg = "#636e72", bg='#f5f6fa', font=('broadway', 18))
labelWindow.grid(column=1, row=0, padx=10, pady=20)

labelPlist = Label(gui,text = "Past Your\n URL Here -->", fg = "#636e72", bg='#f5f6fa')
labelPlist.grid(column=0, row=1, padx=1)

textBox=Text(gui, height=1, width=55, borderwidth=0, bg='#c8d6e5')
textBox.grid(column=1, row=1, padx=1)

buttonDls=Button(gui, height=2, width=13, text="Clear Entry", fg='white', bg='#5599ff', borderwidth=0, command=lambda: eClear())
buttonDls.grid(column=2, row=1, padx=2)

buttonDls=Button(gui, height=2, width=20, text="Download Single Video", fg='white', bg='#5599ff', borderwidth=0, command=lambda: sList_input())
buttonDls.grid(column=1, row=4, padx=10, pady=10)

checkBox = Checkbutton(gui, text = "Download \n Audio Only", fg = "#636e72", bg='#f5f6fa', variable = audioVal )
checkBox.grid(column=2, row=4)

checkBox = Checkbutton(gui, text = "Choose High\n Quality", fg = "#636e72", bg='#f5f6fa', variable = qualityVal )
checkBox.grid(column=2, row=5)

buttonDll=Button(gui, height=2, width=20, text="Download all Playlist", fg='white', bg='#5599ff', borderwidth=0, command=lambda: pList_input())
buttonDll.grid(column=1, row=5)

buttonEx=Button(gui, height=2, width=13, text="Exit", fg='white', bg='#ff7675', borderwidth=0,  command=gui.destroy) 
buttonEx.grid(column=0, row=6, padx=15)


cMenu(gui)
textBox.bind_class("Text", "<Button-3><ButtonRelease-3>", sMenu)
menubar = Menu(gui)

filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="Exit", command=gui.destroy)
menubar.add_cascade(label="File", menu=filemenu)

optionmenu = Menu(menubar, tearoff=0)
optionmenu.add_command(label="Stop All Process", command=lambda: os.system("pkexec killall youtube-dl"))
optionmenu.insert_separator(2)
optionmenu.add_command(label="Open Download Folder", command=lambda: fileCh())
optionmenu.insert_separator(3)
optionmenu.add_command(label="Change Download Location", command=lambda: browsePath())
optionmenu.add_command(label="URL Grabber", command=lambda: os.system("url_grabber"))
optionmenu.insert_separator(5)
menubar.add_cascade(label="Option", menu=optionmenu)

helpmenu = Menu(menubar, tearoff=0)
helpmenu.add_command(label="Check For update", command=lambda: cUpdate())
helpmenu.insert_separator(2)
helpmenu.add_command(label="About", command=lambda: messageBox())
menubar.add_cascade(label="Help", menu=helpmenu)

gui.config(menu=menubar)

gui.geometry("790x370")

mainloop()

